package schemax

import (
	"encoding/json"
	"gitee.com/zhongguo168a/gocodes/myx/logx"
	"reflect"
	"sync"
)

type IDecl interface {
	GetIdent() string
	GetName() string
	GetNamespace() string
	RefType() string
}

func ParseJson(content string) (err error) {
	m := map[string]interface{}{}
	err = json.Unmarshal([]byte(content), &m)
	return
}

var (
	data = &sync.Map{}
)

func GetDeclByKey(key string) IDecl {
	val, has := data.Load(key)
	if !has {
		return nil
	}
	return val.(IDecl)
}

func AddDecls(decls []IDecl) (err error) {
	for _, val := range decls {
		err = AddDecl(val)
		if err != nil {
			return
		}
	}

	return
}

func AddDecl(decl IDecl) (err error) {
	ident := decl.GetName()
	if decl.GetNamespace() != "" {
		ident = decl.GetNamespace() + "/" + ident
	}
	_, has := data.Load(ident)
	if has {
		logx.Warn("存在相同编号的schema声明: " + ident)
	}
	data.Store(ident, decl)
	data.Store(decl.GetName(), decl)
	return
}

func GetDeclByStruct(st interface{}) IDecl {
	decl := GetDeclByKey(GetDeclByStructKey(st))
	if decl == nil {
		decl = CreateDecl(reflect.TypeOf(st))
	}
	return decl
}

func GetDeclByStructKey(st interface{}) string {
	obj, ok := st.(IObject)
	if ok {
		return obj.RefType()
	}
	rtyp := reflect.TypeOf(st)
	if rtyp.Kind() == reflect.Ptr {
		rtyp = rtyp.Elem()
	}
	return rtyp.String()
}
